<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>上传视频 - 局域网视频学习系统</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .upload-container {
            max-width: 800px;
            margin: 0 auto;
        }

        .upload-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            text-align: center;
        }

        .upload-title {
            font-size: 24px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin-bottom: 8px;
        }

        .upload-subtitle {
            color: #666;
            font-size: 14px;
        }

        .upload-steps {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
        }

        .steps-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }

        .step {
            display: flex;
            align-items: center;
            margin: 0 20px;
        }

        .step-number {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #e0e0e0;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 10px;
            transition: all 0.3s ease;
        }

        .step.active .step-number {
            background: var(--teacher-color);
            color: white;
        }

        .step.completed .step-number {
            background: var(--success-color);
            color: white;
        }

        .step-text {
            font-size: 14px;
            color: #666;
        }

        .step.active .step-text {
            color: var(--teacher-color);
            font-weight: 600;
        }

        .step-connector {
            width: 40px;
            height: 2px;
            background: #e0e0e0;
            margin: 0 10px;
        }

        .step.completed + .step .step-connector {
            background: var(--success-color);
        }

        .upload-area {
            border: 2px dashed var(--border-color);
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            background: #fafafa;
            transition: all 0.3s ease;
            cursor: pointer;
            margin-bottom: 20px;
        }

        .upload-area:hover {
            border-color: var(--teacher-color);
            background: rgba(78, 205, 196, 0.05);
        }

        .upload-area.dragover {
            border-color: var(--teacher-color);
            background: rgba(78, 205, 196, 0.1);
        }

        .upload-icon {
            font-size: 48px;
            color: #ccc;
            margin-bottom: 16px;
        }

        .upload-text {
            font-size: 16px;
            color: var(--neutral-dark);
            margin-bottom: 8px;
        }

        .upload-hint {
            font-size: 14px;
            color: #666;
            margin-bottom: 16px;
        }

        .upload-btn {
            background: var(--teacher-color);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .upload-btn:hover {
            background: #3bb5ad;
        }

        .file-info {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            display: none;
        }

        .file-details {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
        }

        .file-icon {
            width: 48px;
            height: 48px;
            background: var(--teacher-color);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
        }

        .file-meta h4 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 4px;
            color: var(--neutral-dark);
        }

        .file-meta p {
            font-size: 12px;
            color: #666;
            margin: 0;
        }

        .progress-container {
            margin-top: 15px;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e0e0e0;
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 8px;
        }

        .progress-fill {
            height: 100%;
            background: var(--teacher-color);
            transition: width 0.3s ease;
            width: 0%;
        }

        .progress-text {
            font-size: 12px;
            color: #666;
            text-align: center;
        }

        .upload-form {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: var(--shadow);
        }

        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-row .form-group {
            flex: 1;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--neutral-dark);
        }

        .form-label .required {
            color: var(--error-color);
        }

        .form-control {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--teacher-color);
            box-shadow: 0 0 0 2px rgba(78, 205, 196, 0.2);
        }

        .form-control.is-invalid {
            border-color: var(--error-color);
        }

        .form-text {
            font-size: 12px;
            color: #666;
            margin-top: 4px;
        }

        .error-message {
            color: var(--error-color);
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }

        .submit-section {
            text-align: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid var(--border-color);
        }

        .submit-btn {
            background: var(--success-color);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 120px;
        }

        .submit-btn:hover {
            background: #45a049;
            transform: translateY(-1px);
        }

        .submit-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .loading {
            display: none;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid var(--teacher-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .success-message {
            background: white;
            border-radius: 8px;
            padding: 30px;
            box-shadow: var(--shadow);
            text-align: center;
            display: none;
        }

        .success-icon {
            font-size: 64px;
            color: var(--success-color);
            margin-bottom: 20px;
        }

        .success-title {
            font-size: 20px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin-bottom: 10px;
        }

        .success-text {
            color: #666;
            margin-bottom: 20px;
        }

        .sidebar-footer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 20px;
            border-top: 1px solid var(--border-color);
        }

        .logout-btn {
            width: 100%;
            padding: 12px 16px;
            background: var(--error-color);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        @media (max-width: 768px) {
            .form-row {
                flex-direction: column;
                gap: 0;
            }
            
            .steps-indicator {
                flex-direction: column;
                gap: 10px;
            }
            
            .step {
                margin: 0;
            }
            
            .step-connector {
                display: none;
            }
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h3>老师工作台</h3>
        </div>
        <ul class="sidebar-nav">
            <li class="nav-item">
                <a href="dashboard.html" class="nav-link">
                    <i>📊</i> 仪表盘
                </a>
            </li>
            <li class="nav-item">
                <a href="upload.html" class="nav-link active">
                    <i>📤</i> 上传视频
                </a>
            </li>
            <li class="nav-item">
                <a href="videos.html" class="nav-link">
                    <i>🎥</i> 视频管理
                </a>
            </li>
            <li class="nav-item">
                <a href="exam-management.html" class="nav-link">
                    <i>📝</i> 考试管理
                </a>
            </li>
            <li class="nav-item">
                <a href="question-management.html" class="nav-link">
                    <i>❓</i> 题目管理
                </a>
            </li>
            <li class="nav-item">
                <a href="profile.html" class="nav-link">
                    <i>👤</i> 个人资料
                </a>
            </li>
        </ul>
        
        <!-- 退出登录 -->
        <div class="sidebar-footer">
            <button class="logout-btn" onclick="UserManager.logout()">
                <i>🚪</i> 退出登录
            </button>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <div class="content-wrapper">
            <div class="upload-container">
                <!-- 页面标题 -->
                <div class="upload-header">
                    <h1 class="upload-title">上传视频</h1>
                    <p class="upload-subtitle">上传您的教学视频，与学生分享知识</p>
                </div>

                <!-- 上传步骤 -->
                <div class="upload-steps">
                    <div class="steps-indicator">
                        <div class="step active" id="step1">
                            <div class="step-number">1</div>
                            <div class="step-text">选择文件</div>
                        </div>
                        <div class="step-connector"></div>
                        <div class="step" id="step2">
                            <div class="step-number">2</div>
                            <div class="step-text">填写信息</div>
                        </div>
                        <div class="step-connector"></div>
                        <div class="step" id="step3">
                            <div class="step-number">3</div>
                            <div class="step-text">提交审核</div>
                        </div>
                    </div>

                    <!-- 文件上传区域 -->
                    <div class="upload-area" id="uploadArea">
                        <div class="upload-icon">📁</div>
                        <div class="upload-text">点击或拖拽视频文件至此处</div>
                        <div class="upload-hint">支持 MP4、AVI、MKV、WebM 格式，最大 500MB</div>
                        <button class="upload-btn" onclick="document.getElementById('fileInput').click()">
                            选择文件
                        </button>
                        <input type="file" id="fileInput" accept="video/*" style="display: none;">
                    </div>

                    <!-- 文件信息 -->
                    <div class="file-info" id="fileInfo">
                        <div class="file-details">
                            <div class="file-icon">🎬</div>
                            <div class="file-meta">
                                <h4 id="fileName">文件名</h4>
                                <p id="fileSize">文件大小</p>
                            </div>
                        </div>
                        <div class="progress-container" id="progressContainer" style="display: none;">
                            <div class="progress-bar">
                                <div class="progress-fill" id="progressFill"></div>
                            </div>
                            <div class="progress-text" id="progressText">上传中... 0%</div>
                        </div>
                    </div>
                </div>

                <!-- 上传表单 -->
                <div class="upload-form" id="uploadForm" style="display: none;">
                    <form id="videoForm">
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label" for="title">视频标题 <span class="required">*</span></label>
                                <input type="text" id="title" name="title" class="form-control" required>
                                <div class="error-message" id="title-error"></div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label" for="intro">视频简介</label>
                            <textarea id="intro" name="intro" class="form-control" rows="4" 
                                      placeholder="简要描述视频内容和学习目标..."></textarea>
                            <div class="form-text">建议填写视频的主要内容、学习目标等信息</div>
                        </div>

                        <div class="form-group">
                            <label class="form-label" for="tags">标签</label>
                            <input type="text" id="tags" name="tags" class="form-control" 
                                   placeholder="用逗号分隔多个标签，如：函数,微积分,数学">
                            <div class="form-text">添加标签有助于学生搜索和分类</div>
                        </div>

                        <div class="submit-section">
                            <button type="submit" class="submit-btn" id="submitBtn">
                                <span class="loading" id="loading"></span>
                                <span id="submitText">提交审核</span>
                            </button>
                        </div>
                    </form>
                </div>

                <!-- 成功消息 -->
                <div class="success-message" id="successMessage">
                    <div class="success-icon">✅</div>
                    <div class="success-title">上传成功！</div>
                    <div class="success-text">您的视频已提交审核，审核通过后将对学生可见。</div>
                    <div style="display: flex; gap: 10px; justify-content: center; margin-top: 20px;">
                        <a href="videos.html" class="btn btn-teacher">查看我的视频</a>
                        <a href="upload.html" class="btn btn-secondary" onclick="resetForm()">继续上传</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 侧边栏切换按钮 -->
    <button class="sidebar-toggle">☰</button>

    <script src="../js/common.js"></script>
    <script>
        let selectedFile = null;
        let currentStep = 1;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查权限
            if (!UserManager.hasPermission(1)) {
                Message.error('权限不足');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 2000);
                return;
            }

            initUploadArea();
            initFormValidation();
        });

        // 初始化上传区域
        function initUploadArea() {
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');

            // 点击上传区域
            uploadArea.addEventListener('click', () => {
                fileInput.click();
            });

            // 文件选择
            fileInput.addEventListener('change', handleFileSelect);

            // 拖拽上传
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });

            uploadArea.addEventListener('dragleave', () => {
                uploadArea.classList.remove('dragover');
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
                
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    handleFile(files[0]);
                }
            });
        }

        // 处理文件选择
        function handleFileSelect(e) {
            const file = e.target.files[0];
            if (file) {
                handleFile(file);
            }
        }

        // 处理文件
        function handleFile(file) {
            // 验证文件
            const validation = FileUpload.validateFile(file);
            if (!validation.isValid) {
                Message.error(validation.errors.join(', '));
                return;
            }

            selectedFile = file;
            showFileInfo(file);
            updateStep(2);
        }

        // 显示文件信息
        function showFileInfo(file) {
            const fileInfo = document.getElementById('fileInfo');
            const fileName = document.getElementById('fileName');
            const fileSize = document.getElementById('fileSize');

            fileName.textContent = file.name;
            fileSize.textContent = Utils.formatFileSize(file.size);

            fileInfo.style.display = 'block';
            document.getElementById('uploadForm').style.display = 'block';
        }

        // 更新步骤
        function updateStep(step) {
            currentStep = step;
            
            // 更新步骤指示器
            for (let i = 1; i <= 3; i++) {
                const stepEl = document.getElementById(`step${i}`);
                stepEl.classList.remove('active', 'completed');
                
                if (i < step) {
                    stepEl.classList.add('completed');
                } else if (i === step) {
                    stepEl.classList.add('active');
                }
            }
        }

        // 初始化表单验证
        function initFormValidation() {
            const form = document.getElementById('videoForm');
            
            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                await submitVideo();
            });

            // 实时验证
            document.getElementById('title').addEventListener('input', function() {
                if (this.value.trim()) {
                    this.classList.remove('is-invalid');
                    document.getElementById('title-error').style.display = 'none';
                }
            });
        }

        // 提交视频
        async function submitVideo() {
            if (!selectedFile) {
                Message.error('请先选择视频文件');
                return;
            }

            const form = document.getElementById('videoForm');
            const formData = new FormData(form);
            
            // 表单验证
            const validation = FormValidator.validate(form);
            if (!validation.isValid) {
                Message.error(validation.errors.join('<br>'));
                return;
            }

            const submitBtn = document.getElementById('submitBtn');
            const loading = document.getElementById('loading');
            const submitText = document.getElementById('submitText');

            // 显示加载状态
            submitBtn.disabled = true;
            loading.style.display = 'inline-block';
            submitText.textContent = '提交中...';

            try {
                // 直接上传文件和信息
                const uploadResponse = await uploadVideoWithInfo(selectedFile, formData, (progress) => {
                    const progressFill = document.getElementById('progressFill');
                    const progressText = document.getElementById('progressText');
                    const progressContainer = document.getElementById('progressContainer');
                    
                    progressContainer.style.display = 'block';
                    progressFill.style.width = progress + '%';
                    progressText.textContent = `上传中... ${Math.round(progress)}%`;
                });

                if (uploadResponse.success) {
                    showSuccessMessage();
                    updateStep(3);
                } else {
                    Message.error(uploadResponse.message || '上传失败');
                }
            } catch (error) {
                console.error('上传失败:', error);
                Message.error('上传失败：' + error.message);
            } finally {
                // 恢复按钮状态
                submitBtn.disabled = false;
                loading.style.display = 'none';
                submitText.textContent = '提交审核';
            }
        }

        // 上传视频和信息
        async function uploadVideoWithInfo(file, formData, onProgress) {
            const data = new FormData();
            data.append('file', file);
            data.append('title', formData.get('title'));
            data.append('intro', formData.get('intro') || '');
            data.append('tags', formData.get('tags') || '');
            
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                
                // 上传进度
                xhr.upload.addEventListener('progress', (e) => {
                    if (e.lengthComputable && onProgress) {
                        const percentComplete = (e.loaded / e.total) * 100;
                        onProgress(percentComplete);
                    }
                });
                
                // 上传完成
                xhr.addEventListener('load', () => {
                    if (xhr.status === 200) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            resolve(response);
                        } catch (error) {
                            reject(new Error('响应格式错误'));
                        }
                    } else {
                        reject(new Error(`上传失败: ${xhr.status}`));
                    }
                });
                
                // 上传错误
                xhr.addEventListener('error', () => {
                    reject(new Error('网络错误'));
                });
                
                xhr.open('POST', '/api/video/upload');
                xhr.send(data);
            });
        }

        // 显示成功消息
        function showSuccessMessage() {
            document.getElementById('uploadForm').style.display = 'none';
            document.getElementById('fileInfo').style.display = 'none';
            document.getElementById('successMessage').style.display = 'block';
        }

        // 重置表单
        function resetForm() {
            selectedFile = null;
            currentStep = 1;
            
            document.getElementById('videoForm').reset();
            document.getElementById('fileInfo').style.display = 'none';
            document.getElementById('uploadForm').style.display = 'none';
            document.getElementById('successMessage').style.display = 'none';
            document.getElementById('progressContainer').style.display = 'none';
            
            updateStep(1);
        }
    </script>
</body>
</html>
